import { makeAutoObservable } from 'mobx';
import React from 'react';

class MainStore {
  // 对应Vue项目中的state
  curView = sessionStorage.getItem('navView') || 1;
  userdata = JSON.parse(localStorage.getItem('userdata')) || {};
  currentPage = 1;

  students = [];
  selectStudent = {};

  constructor() {
    makeAutoObservable(this);
  }

  // 对应Vue项目中的actions
  changeView(num) {
    this.curView = num;
  }

  saveUserData(data) {
    const userInfo = { ...data };
    localStorage.setItem('userdata', JSON.stringify(userInfo));
    // delete userInfo.token;
    this.userdata = userInfo;
  }

  saveStudents(data) {
    const studentInfo = { ...data };
    this.students = studentInfo;
  }

  saveSelectStudent(data) {
    const studentInfo = { ...data };
    this.selectStudent = studentInfo;
  }
}

const mainStore = new MainStore();

// 创建React上下文，用于在组件树中共享store
const StoreContext = React.createContext();

// 提供一个Provider组件，用于在应用顶层包裹
export const StoreProvider = ({ children }) => {
  return (
    <StoreContext.Provider value={mainStore}>
      {children}
    </StoreContext.Provider>
  );
};

// 创建一个自定义钩子，用于在组件中访问store
export const useStore = () => {
  const store = React.useContext(StoreContext);
  if (!store) {
    throw new Error('useStore must be used within a StoreProvider');
  }
  return store;
};

export { mainStore };